import { getPropertyMetadata, Guard, httpError, IGuard } from '@midwayjs/core'
import { Context } from 'koa'

import { PERMISSION_META_KEY } from '@/decorator'
import { LoginUserService } from '@/service'

@Guard()
export class AuthorizationGuard implements IGuard<Context> {
  async canActivate(
    ctx: Context,
    supplierClz: new (...args: any[]) => any,
    methodName: string
  ) {
    const permission = getPropertyMetadata<string>(
      PERMISSION_META_KEY,
      supplierClz,
      methodName
    )

    if (permission) {
      const loginUserService = await ctx.requestContext.getAsync(
        LoginUserService
      )

      const { permissions } = await loginUserService.getCurrentUser()

      if (permissions.includes('*:*:*')) {
        // 管理员权限不做处理
        return true
      } else if (!permissions.includes(permission)) {
        ctx.throw(
          new httpError.ForbiddenError(`无权访问 - ${ctx.method} ${ctx.path}`)
        )
      } else {
        return true
      }
    } else {
      return true
    }
  }
}
